import os, sys, re

FORBIDEN = re.compile(".*\.hg.*")

def __privateFndrep(
		path,
		src,
		goal,
		flsp,
		iterative = False
	):
	if FORBIDEN.match(path):
		print "FORBIDEN: " + path
		return
	if os.path.isfile(path):
		if not flsp.match(path):
			return
		b = open(path, "r").read()
		binit = b
		bprev = None
		while bprev != b:
			bprev = b
			n = len(src)
			for i in xrange(n):
				b = b.replace(src[i], goal[i])
			if not iterative:
				break
		if (binit != b):
			print path
			f = open(path, "w")
			f.write(b)
			f.close()
	else:
		for s in os.listdir(path):
			sp = os.path.join(path, s)
			__privateFndrep(
				sp,
				src,
				goal,
				flsp,
				iterative
			)

def fndrep(path, src, goal, filesre, iterative = False):
	flsp = re.compile(filesre)
	if isinstance(src, str):
		src = [src]
	if isinstance(goal, str):
		goal = [goal]
	__privateFndrep(
		os.path.normpath(os.path.abspath(path)),
		src,
		goal,
		flsp,
		iterative
	)

def normarg(arg):
	return arg.replace("\\t", "\t").replace("\\n", "\n")

if __name__ == "__main__":
	filesre = ".*"
	if len(sys.argv) > 3:
		filesre = sys.argv[3]
	fndrep(".", normarg(sys.argv[1]), normarg(sys.argv[2]), filesre)